package com.ruoyi.common.utils.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
import com.ruoyi.common.utils.AliyunOssUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.StringUtils;

/**
 * 文件上传工具类
 * 
 * @author ruoyi
 */
public class FileUploadUtils
{
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认上传的地址
     */
    private static String defaultBaseDir = Global.getProfile();

    /**
     * 默认文件类型jpg
     */
    public static final String IMAGE_JPG_EXTENSION = ".jpg";
	private static final String UPLOAD_RESULT_OK = "OK";		//上传成功
	private static final String  UPLOAD_RESULT_ERROR = "ERROR"; //上传失败
    
    private static int counter = 0;

    public static void setDefaultBaseDir(String defaultBaseDir)
    {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir()
    {
        return defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload(MultipartFile file) throws IOException
    {
        try
        {
            return upload(getDefaultBaseDir(), file, FileUploadUtils.IMAGE_JPG_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException
    {
        try
        {
            return upload(baseDir, file, FileUploadUtils.IMAGE_JPG_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @param extension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException 比如读写文件出错时
     */
    public static final String upload(String baseDir, MultipartFile file, String extension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException
    {

        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file);

        String fileName = extractFilename(file, extension);

        File desc = getAbsoluteFile(baseDir, baseDir + fileName);
        file.transferTo(desc);
        return fileName;
    }

    public static final String extractFilename(MultipartFile file, String extension)
    {
        String filename = file.getOriginalFilename();
        filename = DateUtils.datePath() + "/" + encodingFilename(filename) + extension;
        return filename;
    }

    private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException
    {
        File desc = new File(File.separator + filename);

        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists())
        {
            desc.createNewFile();
        }
        return desc;
    }

    /**
     * 编码文件名
     */
    private static final String encodingFilename(String filename)
    {
        filename = filename.replace("_", " ");
        filename = Md5Utils.hash(filename + System.nanoTime() + counter++);
        return filename;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     */
    public static final void assertAllowed(MultipartFile file) throws FileSizeLimitExceededException
    {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
        {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }
    }
    
    /**
     * 文件分区随机写入
     * @param in
     * @param fullFilename
     * @return
     * @throws IOException
     */
    public static String randomAccessFile(InputStream in, String fullpath, long filesize) throws IOException{
        RandomAccessFile  raFile = null;
        try{
            File dirFile = new File(fullpath);
            if (dirFile.exists()) {
            	if(dirFile.length() >= filesize) {
            		return UPLOAD_RESULT_ERROR;
            	}
            }
        	//以读写的方式打开目标文件
        	raFile = new RandomAccessFile(dirFile, "rw"); 
        	//设置指针绝对位置
        	raFile.seek(raFile.length());
        	byte[] buf = new byte[1024];
        	int length = 0;
        	while ((length = in.read(buf)) > 0) {
        		raFile.write(buf, 0, length);
        	}
        	return UPLOAD_RESULT_OK;
        }catch(IOException e){
        	e.printStackTrace();
        	return UPLOAD_RESULT_ERROR;
        }finally{
            try {
                if (in != null) {
                	in.close();
                }
                if (raFile != null) {
                    raFile.close();
                }
            }catch(IOException e){
            	e.printStackTrace();
            	return UPLOAD_RESULT_ERROR;
            }
        }
    }
    
    /**
   	 * 图片上传到阿里云
   	 * @param prefix  图片前缀
   	 * @return
   	 * @throws FileUploadException 
   	 * @throws IOException 
   	 */
   	public synchronized static Map<String, Object>  uploadByAliyun(MultipartFile multipartFile, String prefix) throws FileUploadException, IOException {
   		Map<String, Object> results = new HashMap<>();
   		InputStream in = null;
   		in = multipartFile.getInputStream();
   		//上传图片
   		String uuid = StringUtils.randomUUID();
   		String path = String.format("%s/%s.png", prefix,
   				uuid);
   		String path_url = AliyunOssUtil.upload(path, in);
   		if (StringUtils.isEmpty(path_url)) {
   			results.put("status", BusinessStatus.FAIL);
   			results.put("msg", "上传失败");
   			return results;
   		}
   		results.put("status", BusinessStatus.SUCCESS);
   		results.put("msg", "上传成功");
   		results.put("url", path_url);
   		return results;
   	}
    
    
}
